package com.guoguo.utils;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.enums.SMSEnum;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by Administrator on 2017/9/20 0020.
 */

     /*
                           _ooOoo_
                          o8888888o
                          88" . "88
                          (| -_- |)
                          O\  =  /O
                       ____/`---'\____
                     .'  \\|     |//  `.
                    /  \\|||  :  |||//  \
                   /  _||||| -:- |||||-  \
                   |   | \\\  -  /// |   |
                   | \_|  ''\---/''  |   |
                   \  .-\__  `-`  ___/-. /
                 ___`. .'  /--.--\  `. . __
              ."" '<  `.___\_<|>_/___.'  >'"".
             | | :  `- \`.;`\ _ /`;.`/ - ` : | |
             \  \ `-.   \_ __\ /__ _/   .-` /  /
        ======`-.____`-.___\_____/___.-`____.-'======
                           `=---='
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 佛祖保佑       永无BUG
        */
public class SMSHxUtils {

    private static final String fileName = "sms.properties";

    /**
     * 给多个手机发送短信
     *
     * @param mobileList
     * @param message
     * @return
     */
    public static String sendMassage(List<String> mobileList, String message, boolean isEncryption) {
        String result = HttpClientUtils.doPost(getSmsUrl(isEncryption), sendDataMap(mobileList, message, isEncryption), "utf-8");
        return result;
    }

    /**
     * 给多个手机发送短信
     *
     * @param mobileList
     * @param message
     * @return
     */
    public static String sendMassage(List<String> mobileList, String message) {
        String result = HttpClientUtils.doPost(getSmsUrl(false), sendDataMap(mobileList, message, false), "utf-8");
        return result;
    }

    /**
     * 给单个手机发送短信
     *
     * @param mobile
     * @param message
     * @return
     */
    public static String sendMassage(String mobile, String message, boolean isEncryption) {
        List<String> mobileList = new ArrayList<String>();
        mobileList.add(mobile);
        String result = HttpClientUtils.doPost(getSmsUrl(isEncryption), sendDataMap(mobileList, message, isEncryption), "utf-8");
        return result;
    }

    /**
     * 给单个手机发送短信
     *
     * @param mobile
     * @param message
     * @return
     */
    public static String sendMassage(String mobile, String message) {
        List<String> mobileList = new ArrayList<String>();
        mobileList.add(mobile);
        String result = HttpClientUtils.doPost(getSmsUrl(false), sendDataMap(mobileList, message, false), "utf-8");
        return result;
    }

    /**
     * 根据是否加密切换请求url
     *
     * @param isEncryption
     * @return
     */
    private static String getSmsUrl(boolean isEncryption) {
        if (isEncryption) {
            return PropertyUtils.getProperty(fileName, SMSEnum.SMS_SEND_JSON_EN_URL.getValue());
        } else {
            return PropertyUtils.getProperty(fileName, SMSEnum.SMS_SEND_JSON_URL.getValue());
        }
    }

    private static Map<String, String> sendDataMap(List<String> mobileList, String message, boolean isEncryption) {
        if (isEncryption) {
            return sendEnDataMap(mobileList, message);
        } else {
            return sendDataMap(mobileList, message);
        }

    }

    /**
     * 组装发送参数
     *
     * @param mobileList
     * @param message
     * @return
     */
    private static Map<String, String> sendDataMap(List<String> mobileList, String message) {
        StringBuffer mobileString = new StringBuffer();
        for (String mobile : mobileList) {
            mobileString.append(mobile).append(",");
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("userid", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_USERID.getValue()));
        data.put("account", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_ACCOUNT.getValue()));
        String password = MD5Utils.encrypt(PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_PASSWORD.getValue()));
        data.put("password", password.toUpperCase());
        data.put("mobile", mobileString.subSequence(0, mobileString.length() - 1).toString());
        data.put("content", message);
        data.put("sendTime", DateUtils.getDateByFormat(new Date(), "yyyy-MM-dd hh:mm:ss"));
        data.put("action", SMSEnum.SMS_ACTION_SEND.getValue());
        data.put("extno", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_EXTNO.getValue()));
        return data;
    }

    /**
     * 组装加密发送参数（未完成）
     *
     * @param mobileList
     * @param message
     * @return
     */
    private static Map<String, String> sendEnDataMap(List<String> mobileList, String message) {
        StringBuffer mobileString = new StringBuffer();
        for (String mobile : mobileList) {
            mobileString.append(mobile).append(",");
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("UserId", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_USERID.getValue()));

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UserName", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_ACCOUNT.getValue()));
        String stamp = DateUtils.getDateByFormat(new Date(), "MMddHHmmss");
        jsonObject.put("Stamp", stamp);
        String secret = MD5Utils.encrypt(PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_PASSWORD.getValue()) + stamp);
        jsonObject.put("Secret", secret.toUpperCase());
        jsonObject.put("Moblie", mobileString.subSequence(0, mobileString.length() - 1).toString());
        jsonObject.put("Text", message);
        jsonObject.put("Ext", PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_EXTNO.getValue()));
        jsonObject.put("SendTime", "");
        String text64 = "";
        try {
            byte[] content = jsonObject.toJSONString().getBytes("utf8");

            byte[] key = getKey(PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_PASSWORD.getValue()));// PropertyUtils.getProperty(fileName, SMSEnum.SMS_PARAMETER_PASSWORD.getValue()).getBytes();

            byte[] bytes = DesUtils.DES_CBC_Encrypt(content, key);

            BASE64Encoder encoder = new BASE64Encoder();
            text64 = encoder.encode(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            data.put("Text64", java.net.URLEncoder.encode(text64, "utf8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 获取key
     *
     * @param passowrd
     * @return
     */
    private static byte[] getKey(String passowrd) {
        byte[] tempKey = passowrd.getBytes();
        byte[] key = new byte[8];
        if (tempKey.length < 8) {
            for (int i = tempKey.length; i < 8; i++) {
                key[i] = 0;
            }
        } else if (tempKey.length >= 8) {
            System.arraycopy(tempKey, 0, key, 0, 8);
        }
        return key;
    }
}
